
package network.sslProxy;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Date;

import network.utils.ProxyConstants;

/**
 * Thread which receive CONNECT Command from user and send it to Local SSL
 * Server.
 * 
 * @author http://arunava.in
 * 
 */
public class SSLProxyHandler extends Thread {

	private Socket socket = null;

	public SSLProxyHandler(final Socket socket) {
		this.socket = socket;
	}

	public void run() {
		if (ProxyConstants.logLevel >= 1) {
			System.out.println(new Date()
					+ " SSLProxyHandler :: ProxyHandler Started "
					+ currentThread());
		}
		try {
			final OutputStream os = socket.getOutputStream();
			final InputStream is = socket.getInputStream();

			if (ProxyConstants.logLevel >= 1) {
				System.out.println("Reading header :: ProxyHandler "
						+ currentThread());
			}
			int rdL;
			final StringBuffer sb = new StringBuffer(9999);
			while (true) {
				rdL = is.read();
				if (rdL == -1) {
					break;
				}
				sb.append((char) rdL);
				if (sb.indexOf("\r\n\r\n") != -1) {
					break;
				}
			}
			if (ProxyConstants.logLevel >= 2) {
				System.out.println(new Date()
						+ " SSLProxyHandler : Header Received from browser ::"
						+ currentThread() + "\n\n" + sb);
			}
			if (ProxyConstants.logLevel >= 2) {
				System.out
						.println(new Date()
								+ " SSLProxyHandler : Header Reading completing :: Checking protocol "
								+ currentThread());
			}

			if (sb.toString().toLowerCase().startsWith("connect")) {
				if (ProxyConstants.logLevel >= 2) {
					System.out
							.println(new Date()
									+ " SSLProxyHandler :: Its a SSL ( Connect ) request"
									+ currentThread());
				}
				new SSLProxy(socket, is, os, sb.toString()).start();
			}
			if (ProxyConstants.logLevel >= 1) {
				System.out
						.println(new Date()
								+ " SSLProxyHandler :: Child Threads are started :: Own Finish "
								+ currentThread());
			}
		} catch (final Exception exp) {
			if (ProxyConstants.logLevel >= 1) {
				System.out.println(new Date() + " SSLProxyHandler :: Error "
						+ currentThread() + " " + exp);
			}
		}
	}
}